<?php

namespace app\common\library;

use fast\Random;

/**
 * 有道翻译接口
 * @classname Yunda
 * @package app\common\library
 */
class Youdao
{
    public string $url       = 'https://openapi.youdao.com/api';
    public string $appId     = '729525389fe24d6e';
    public string $appKey    = 'a0V5XRCD5zJcoFJwrmZxoafrybnxTIvj';
    public string $signType  = 'v3';
    public string $from      = 'auto';


    /**
     *语种格式化
     * @return string[]
     *
     */
    public function getToLIst(): array
    {
        return ['russian'=>'mn','zh-CN'=>'zh-CHS','en'=>'en'];
    }

    /**
     * 发送请求
     **
     * @param $q
     * @param $to
     * @return mixed
     * @throws \Exception
     */
    public function send($q,$to){
        $data['q'] = $q;
        $data['from'] = $this->from;
        $data['to'] = $this->getToLIst()[$to];
        $data['appKey'] = $this->appId;
        $data['salt'] = Random::uuid();
        $data['signType'] = $this->signType;
        $data['curtime'] = time();
        $data['sign'] = calculateSignature(
            $data['appKey'],
            $data['q'],
            $data['salt'],  // 需与上方一致
            $data['curtime'],
            $this->appKey
        );
        $url = 'https://openapi.youdao.com/api';
        $data =  httpGetRequest($url,$data);
        $body = [];
        if($data['status'] == 200){
            $body = json_decode($data['body'],true);
        }
       return $body;
    }
}
